package com.bestcem.xm.qdes.handler.impor.type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.qdes.handler.impor.KeyWordHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class KeywordMatrixrowGroupHandler implements KeyWordHandler {
    private static final Pattern ATTR_PATTERN = Pattern.compile("\\[(.*?)\\]");

    @Override
    public Integer handler(String qType, JSONArray rawItems, JSONObject questionDict) {
        // 矩阵行分组解析
        //    {
        //        id: "36_1",
        //        title: "分组1",
        //        fixed: false,
        //        items: [{
        //            gid: 39,
        //            oid: 1}],
        //        disp_code: "1==1"
        //    }
        if (rawItems == null || rawItems.isEmpty()) {
            return 0;
        }

        JSONArray rowMatrixGroupCommon = Optional.ofNullable(rawItems.getJSONArray(0)).orElse(new JSONArray());
        String matrixGroupAttrStr = rowMatrixGroupCommon.size() > 2 ? rowMatrixGroupCommon.getString(2).trim() : "";
        questionDict.putAll(parseMatrixGroupCommonAttr(matrixGroupAttrStr));

        JSONArray rawMatrixGroups = new JSONArray();
        if (rowMatrixGroupCommon.size() > 1) {
            for (int i = 1; i < rawItems.size(); i++) {
                rawMatrixGroups.add(rawItems.get(i));
            }
        }
        String dispSelect = Optional.ofNullable(questionDict.getString("dispSelect")).orElse("");

        if (rawMatrixGroups.size() > 0) {
            questionDict.put("rowsGroupEffect", true);
        }

        JSONArray retItems = new JSONArray();
        questionDict.put("row_group_list", retItems);

        int totalGidCountTmp = 0;
        for (int i = 0; i < rawMatrixGroups.size(); i++) {
            JSONArray rawMatrixGroup = rawMatrixGroups.getJSONArray(i);
            JSONObject optionGroupDict = new JSONObject();
            Object optionGroupTitle = rawMatrixGroup.get(0);
            List<String> optionCids = (rawMatrixGroup.size() > 1 && StringUtils.isNotEmpty(rawMatrixGroup.getString(1).trim()))
                ? Arrays.stream(rawMatrixGroup.getString(1).trim().split(",")).collect(Collectors.toList())
                : new ArrayList<>();

            JSONArray itemsJs = new JSONArray();
            for (String cid : optionCids) {
                if (StringUtils.isNotEmpty(cid)) {
                    JSONObject cidJs = new JSONObject();
                    cidJs.put("oid", cid);
                    itemsJs.add(cidJs);
                }
            }
            optionGroupDict.put("items", itemsJs);

            String matrixGroupAttr = rawMatrixGroup.size() > 2 ? rawMatrixGroup.getString(2) : "";
            if ("[固定]".equals(matrixGroupAttr)) {
                optionGroupDict.put("fixed", true);
            }
            String optionGroupDispCode = rawMatrixGroup.size() > 3 ? rawMatrixGroup.getString(3) : "";
            if (StringUtils.isNotEmpty(optionGroupDispCode) && "1".equals(dispSelect)) {
                optionGroupDict.put("disp_code", optionGroupDispCode);
            }

            optionGroupDict.put("title", optionGroupTitle);
            retItems.add(optionGroupDict);
        }
        return totalGidCountTmp;
    }

    @Override
    public String getType() {
        return "矩阵行分组";
    }

    private JSONObject parseMatrixGroupCommonAttr(String attrstr) {
        // 解析矩阵行分组标签的属性设置
        JSONObject retDict = new JSONObject();
        if (StringUtils.isEmpty(attrstr)) {
            return retDict;
        }

        // [顺序#默认][显示组名] --> ['顺序#默认', '显示组名']
        Matcher attrMatcher = ATTR_PATTERN.matcher(attrstr);
        List<String> attributes = new ArrayList<>();
        while (attrMatcher.find()) {
            attributes.add(attrMatcher.group(1));
        }

        for (String attr : attributes) {
            attr = attr.trim();
            if (attr.startsWith("顺序#")) {
                String[] vals = attr.split("#");
                if (vals.length > 1) {
                    String dispVal = attr.split("#")[1];
                    retDict.put("rows_group_random", "随机".equals(dispVal) ? true : "循环".equals(dispVal) ? "sort" : "倒序"
                        .equals(dispVal) ? "reverse" : false);
                }
            } else if ("不显示组名".equals(attr)) {
                retDict.put("showRowsGroupTitle", false);
            } else if ("显示组名".equals(attr)) {
                retDict.put("showRowsGroupTitle", true);
            }
        }
        return retDict;
    }
}
